import urllib
import urllib2
import re
import random

class RandomWord(object):
	def __init__(self, type, complexity):
		args = urllib.urlencode({
								self.WORD_TYPE_ID: self.WORD_TYPES[type],
								self.WORD_COMPLEX_ID: self.WORD_COMPLEXITY[complexity]
								})
		url = urllib2.urlopen(self.RAND_WORD_URL, args)
		response = url.read()
		self.word = re.findall(self.RAND_WORD_PAT, response)[0]
	
	def __repr__(self):
		return self.word
		
	def __str__(self):
		return self.word
	
	WORD_TYPE_ID = "tmpl_main_drpPos"
	WORD_TYPES = {
				"n": "Noun",
				"a": "Adjective",
				"t": "Verb (Transitive)",
				"i": "Verb (Intransitive)",
				"e": "Adverb",
				"z": "Interjection",
				"s": "Preposition",
				}
	WORD_TYPES = dict([(v,k) for k, v in WORD_TYPES.iteritems()])
	#WORD_TYPES.update([(v,k) for k, v in WORD_TYPES.iteritems()])

	WORD_COMPLEX_ID = "tmpl_main_drpLevel"
	WORD_COMPLEXITY = {
					"10": "Very Common",
					"20": "Common",
					"35": "Average",
					"50": "Somewhat Uncommon",
					"60": "Uncommon",
					"70": "Very Uncommon",
					"95": "Obscure",
					}
	WORD_COMPLEXITY = dict([(v,k) for k, v in WORD_COMPLEXITY.iteritems()])
	#WORD_COMPLEXITY.update([(v,k) for k, v in WORD_COMPLEXITY.iteritems()])

	RAND_WORD_URL = "http://watchout4snakes.com/creativitytools/RandomWord/RandomWordPlus.aspx"
	RAND_WORD_PAT = r'(?<=<span id="tmpl_main_lblWord" class="randomWord">)[A-Za-z]*?(?=</span></td>)'

	
class RandomPhrase(object):
	def __init__(self):
		self.phrase = "%s"%RandomWord(random.choice(RandomWord.WORD_TYPES.keys()), "Common")
		
	def __repr__(self):
		return self.phrase
		
	def __str__(self):
		return self.phrase
		

if "__main__" == __name__:
	print RandomPhrase()
		